﻿using Faser_Shop.Utils;
using Microsoft.AspNetCore.Mvc;
using System.Linq;

namespace Faser_Shop.Configs
{
    public class ApiBehaviorConfigure
    {
        static public void Options(ApiBehaviorOptions options)
        {
            options.InvalidModelStateResponseFactory = InvalidModelStateResponseFactory;
        }

        static public ActionResult InvalidModelStateResponseFactory(ActionContext actionContext)
        {
            var errors = actionContext.ModelState
            .Where(e => e.Value.Errors.Count > 0)
            .ToDictionary(e => e.Key, e => e.Value.Errors.Select(x => x.ErrorMessage));

            var msg = string.Join(" | ", errors.Select(x => string.Join(" | ", x.Value)));

            return new ObjectResult(ApiResult.ModelValidationFailed(msg, errors));
        }
    }
}
